import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { AlertTriangle, RefreshCw } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { getCaptcha, login } from '../../api/authApi';
import './AdminLogin.css';

function AdminLogin() {
  const navigate = useNavigate();
  const { login: authLogin, isAuthenticated } = useAuth();
  const canvasRef = useRef(null);

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [captchaId, setCaptchaId] = useState('');
  const [captchaAnswer, setCaptchaAnswer] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (isAuthenticated) {
      navigate('/admin');
    }
    fetchCaptcha();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated, navigate]);

  // 绘制 Canvas 验证码
  const drawCaptcha = (text) => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    const width = canvas.width;
    const height = canvas.height;

    // 清空画布
    ctx.clearRect(0, 0, width, height);

    // 绘制渐变背景
    const gradient = ctx.createLinearGradient(0, 0, width, height);
    gradient.addColorStop(0, '#f0f4ff');
    gradient.addColorStop(1, '#e8f0ff');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, width, height);

    // 绘制干扰线
    for (let i = 0; i < 3; i++) {
      ctx.strokeStyle = `rgba(${Math.random() * 100 + 100}, ${Math.random() * 100 + 100}, ${Math.random() * 100 + 150}, 0.3)`;
      ctx.lineWidth = 1.5;
      ctx.beginPath();
      ctx.moveTo(Math.random() * width, Math.random() * height);
      ctx.bezierCurveTo(
        Math.random() * width, Math.random() * height,
        Math.random() * width, Math.random() * height,
        Math.random() * width, Math.random() * height
      );
      ctx.stroke();
    }

    // 绘制验证码文字
    const chars = text.split('');
    const charWidth = width / chars.length;
    
    chars.forEach((char, index) => {
      // 随机颜色
      const hue = Math.random() * 60 + 200; // 蓝色调
      ctx.fillStyle = `hsl(${hue}, 70%, 45%)`;
      
      // 随机字体大小
      const fontSize = 32 + Math.random() * 8;
      ctx.font = `bold ${fontSize}px Arial, sans-serif`;
      
      // 随机旋转角度
      const angle = (Math.random() - 0.5) * 0.4;
      
      // 计算位置
      const x = charWidth * index + charWidth / 2;
      const y = height / 2 + 5;
      
      ctx.save();
      ctx.translate(x, y);
      ctx.rotate(angle);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(char, 0, 0);
      ctx.restore();
    });

    // 绘制干扰点
    for (let i = 0; i < 30; i++) {
      ctx.fillStyle = `rgba(${Math.random() * 150 + 100}, ${Math.random() * 150 + 100}, ${Math.random() * 150 + 100}, 0.3)`;
      ctx.beginPath();
      ctx.arc(
        Math.random() * width,
        Math.random() * height,
        Math.random() * 2 + 1,
        0,
        Math.PI * 2
      );
      ctx.fill();
    }
  };

  const fetchCaptcha = async () => {
    try {
      const data = await getCaptcha();
      setCaptchaId(data.captchaId);
      
      // 使用后端返回的算术题作为显示文本
      // 例如："3 + 5 = ?" 显示为 "3+5=?"
      const displayText = data.question.replace(/\s/g, '');
      setCaptchaAnswer('');
      setError('');
      
      // 等待下一帧再绘制
      setTimeout(() => drawCaptcha(displayText), 0);
    } catch (err) {
      setError('获取验证码失败: ' + err.message);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const response = await login(username, password, captchaId, captchaAnswer);
      authLogin(response.token, username);
      navigate('/admin');
    } catch (err) {
      setError(err.message);
      fetchCaptcha();
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="admin-login">
      <div className="login-background">
        <div className="gradient-orb orb-1"></div>
        <div className="gradient-orb orb-2"></div>
        <div className="gradient-orb orb-3"></div>
      </div>

      <div className="login-container apple-fade-in">
        <div className="login-card apple-card apple-glass">
          <div className="login-header">
            <div className="logo-circle">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 2L2 7L12 12L22 7L12 2Z"/>
                <path d="M2 17L12 22L22 17"/>
                <path d="M2 12L12 17L22 12"/>
              </svg>
            </div>
            <h1>管理员登录</h1>
            <p>几何模型管理系统</p>
          </div>

          <form onSubmit={handleSubmit} className="login-form">
            {error && (
              <div className="error-banner">
                <AlertTriangle size={18} />
                <span>{error}</span>
              </div>
            )}

            <div className="form-group">
              <label htmlFor="username">用户名</label>
              <input
                id="username"
                type="text"
                className="apple-input"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="请输入用户名"
                required
                autoComplete="username"
              />
            </div>

            <div className="form-group">
              <label htmlFor="password">密码</label>
              <input
                id="password"
                type="password"
                className="apple-input"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="请输入密码"
                required
                autoComplete="current-password"
              />
            </div>

            <div className="form-group">
              <label htmlFor="captcha">验证码</label>
              <div className="captcha-group">
                <canvas
                  ref={canvasRef}
                  width={160}
                  height={60}
                  className="captcha-canvas"
                  onClick={fetchCaptcha}
                  title="点击刷新验证码"
                />
                <input
                  id="captcha"
                  type="text"
                  className="apple-input"
                  value={captchaAnswer}
                  onChange={(e) => setCaptchaAnswer(e.target.value)}
                  placeholder="请输入验证码"
                  required
                  autoComplete="off"
                />
                <button
                  type="button"
                  className="apple-button apple-button-secondary refresh-btn"
                  onClick={fetchCaptcha}
                  title="刷新验证码"
                >
                  <RefreshCw size={20} />
                </button>
              </div>
            </div>

            <button
              type="submit"
              className="apple-button apple-button-primary submit-btn"
              disabled={loading}
            >
              {loading ? '登录中...' : '登录'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

export default AdminLogin;

